package org.bizming.record.service;

import java.util.List;

import org.bizming.base.BaseException;
import org.bizming.record.dao.RecordDao;
import org.bizming.record.model.Record;
import org.bizming.record.model.RecordTypeErrCode;
import org.bizming.util.StringHelper;

public class RecordServiceImpl implements RecordService {

	private RecordDao recordDao;

	public boolean add(Record record) throws BaseException {
		if (record.getTypeId() == null) {
			throw new BaseException(RecordTypeErrCode.TYPE_ID_INVALID);
		}
		if (record.getCost() == null) {
			throw new BaseException(RecordTypeErrCode.COST_INVALID);
		}
		if (!StringHelper.isLengthIn(record.getMark(), 300)) {
			throw new BaseException(RecordTypeErrCode.MARK_INVALID);
		}
		if (!StringHelper.isLengthIn(record.getDescription(), 300)) {
			throw new BaseException(RecordTypeErrCode.DESCRIPTION_INVALID);
		}
		record.setCreateTime(System.currentTimeMillis() / 1000);
		record.setActionTime(System.currentTimeMillis() / 1000);
		if (StringHelper.isEmpty(record.getUsername())) {
			record.setUsername("admin");
		}
		return recordDao.add(record);
	}

	public boolean update(Record record) throws BaseException {
		if (record.getTypeId() == null) {
			throw new BaseException(RecordTypeErrCode.TYPE_ID_INVALID);
		}
		if (record.getCost() == null) {
			throw new BaseException(RecordTypeErrCode.COST_INVALID);
		}
		if (!StringHelper.isLengthIn(record.getMark(), 300)) {
			throw new BaseException(RecordTypeErrCode.MARK_INVALID);
		}
		if (!StringHelper.isLengthIn(record.getDescription(), 300)) {
			throw new BaseException(RecordTypeErrCode.DESCRIPTION_INVALID);
		}

		record.setActionTime(System.currentTimeMillis() / 1000);
		if (StringHelper.isEmpty(record.getUsername())) {
			record.setUsername("admin");
		}
		return recordDao.update(record);
	}

	public Record get(int id) {
		return recordDao.get(id);
	}

	public List<Record> selectList(int page, int pages) {
		return recordDao.selectList((page - 1) * page, pages);
	}

	public int count() {
		return recordDao.count();
	}

	// =============================
	public RecordDao getRecordDao() {
		return recordDao;
	}

	public void setRecordDao(RecordDao recordDao) {
		this.recordDao = recordDao;
	}

}
